package com.looeyWei;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashMap;

public class LoginPage implements ActionListener {

    HashMap<String, String> loginInfo = new HashMap<>();

    /**
     * 组件
     */
    JFrame frame = new JFrame("login");
    JButton loginBtn =  new JButton("Login");
    JButton resetBtn =  new JButton("Reset");
    JTextField userIdField = new JTextField();
    JPasswordField passwdField = new JPasswordField();
    JLabel userLabel = new JLabel("user id: ");
    JLabel passwdLabel = new JLabel("passwd: ");
    JLabel messageLabel = new JLabel();

    LoginPage(HashMap<String, String> loginInfo){
        this.loginInfo = loginInfo;

        //
        userLabel.setBounds(50, 100, 75, 25);
        passwdLabel.setBounds(50, 150, 75, 25);
        frame.add(userLabel);
        frame.add(passwdLabel);
        messageLabel.setBounds(125, 250, 250, 35);
        messageLabel.setFont(new Font(null, Font.ITALIC, 25));
        frame.add(messageLabel);

        //
        userIdField.setBounds(125, 100, 200, 25);
        passwdField.setBounds(125, 150, 200, 25);
        frame.add(userIdField);
        frame.add(passwdField);

        //
        loginBtn.setBounds(125, 200, 100, 25);
        loginBtn.addActionListener(this);
        loginBtn.setFocusable(false);
        resetBtn.setBounds(225, 200, 100, 25);
        resetBtn.addActionListener(this);
        resetBtn.setFocusable(false);
        frame.add(loginBtn);
        frame.add(resetBtn);

        // 布局
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(420, 420);
        frame.setLayout(null);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == resetBtn){
            userIdField.setText("");
            passwdField.setText("");
        }else if(e.getSource() == loginBtn){
            String userID = userIdField.getText();
            String passwd = String.valueOf(passwdField.getPassword());

            if(loginInfo.containsKey(userID)){
                if(loginInfo.get(userID).equals(passwd)){
                    messageLabel.setForeground(Color.green);
                    messageLabel.setText("Login successful");
                    frame.dispose();
                    WelcomePage welcomePage = new WelcomePage(userID);
                }else{
                    messageLabel.setForeground(Color.red);
                    messageLabel.setText("Wrong passwd");
                }
            }else{
                messageLabel.setForeground(Color.red);
                messageLabel.setText("username not found");
            }
        }
    }
}
